package com.hjw.httpclient.demo;

import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Test;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.net.URISyntaxException;

/**
 * 设置请求的访问代理对象
 *
 * @author hjwStrart
 * @time 2022-11-20 9:33
 * @version: 1.0
 */
public class Demo5 {


    /**
     * 设置请求代理很可能会导致连接超时，毕竟是免费的。。。
     * @throws Exception
     */
    @Test
    public void method() throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
//        String urlStr = "www.baidu.com";  定义urlStr时，不携带 "http://" 会报 Target host is not specified异常
        String urlStr = "http://www.baidu.com";
        URIBuilder builder = new URIBuilder(urlStr);
        HttpGet httpGet = new HttpGet(builder.build().toString());
        String proxyIp = "114.7.192.253";  // 代理对象IP
        int proxyPort = 8080; // 代理对象端口
        // 创建请求代理对象
        HttpHost httpHost = new HttpHost(proxyIp, proxyPort);
        // 对每一个请求进行配置，会覆盖全局的默认请求配置
        RequestConfig requestConfig = RequestConfig.custom()
                .setProxy(httpHost)  // 设置请求的访问代理
                .build();
        httpGet.setConfig(requestConfig);
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        try {
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
                System.out.println("请求成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
